﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace DSPL.Contracts.DataGridBehaviours
{
    public class DatagridRowBehaviour
    {

        public static bool GetIsSyncWithCurrentItem(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsSyncWithCurrentItemProperty);
        }

        public static void SetIsSyncWithCurrentItem(DependencyObject obj, bool value)
        {
            obj.SetValue(IsSyncWithCurrentItemProperty, value);
        }

        // Using a DependencyProperty as the backing store for IsSyncWithCurrentItem.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsSyncWithCurrentItemProperty =
            DependencyProperty.RegisterAttached("IsSyncWithCurrentItem", typeof(bool), typeof(DataGrid), new PropertyMetadata(false, OnIsSyncWithCurrentItemPropertyChanged));

        private static void OnIsSyncWithCurrentItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DataGrid dataGrid = d as DataGrid;

            if ((bool)e.NewValue)
            {
                dataGrid.CellEditEnding -= dataGrid_CellEditEnding;
                dataGrid.CurrentCellChanged -= dataGrid_CurrentCellChanged;
                dataGrid.CellEditEnding += dataGrid_CellEditEnding;
                dataGrid.CurrentCellChanged += dataGrid_CurrentCellChanged;
            }
        }

        static void dataGrid_CurrentCellChanged(object sender, EventArgs e)
        {
            DataGrid dataGrid = sender as DataGrid;

            DataRowView row = dataGrid.CurrentItem as DataRowView;

            if (row != null)
            {
                row.EndEdit();
            }
        }

        static void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            DataGrid dataGrid = sender as DataGrid;

            DataView dv = dataGrid.ItemsSource as DataView;

            DataTable dt = dv.Table;

            int count = dt.Rows.Count;

            int currentIndex = dataGrid.Items.IndexOf(e.Row.Item);

            if (dt != null && count - 1 == currentIndex)
            {
                DataRow dr = dt.NewRow();
                dt.Rows.Add(dr);
            }

        }
    }
}